package com.service.admin;

import com.bean.pojo.User;
import com.bean.vo.user.AllUserVO;
import com.dao.admin.AdminMapper;
import com.dao.admin.UserMapper;
import com.utils.MybatisUtils;
import com.utils.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 晓帆
 * @description:
 * @create: 2021-06-17 10:31
 **/
public class UserManagementServiceImplement implements UserManagementService{

    /**
     * @Author xiao-fan
     * @Description  展示所有用户信息
     * @Date 10:33 2021/6/17
     **/
    @Override
    public List<AllUserVO> showAllUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectAllUser();
        sqlSession.close();
        ArrayList<AllUserVO> allUserVOArrayList = conversionListUserToListAllUserVO(userList);
        return allUserVOArrayList;
    }

    /**
 * @Author xiao-fan
 * @Description  删除User
 * @Date 10:34 2021/6/17
 **/
    @Override
    public int deleteUser(Integer id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        if (id==1){
            return 404;
        }
        int deleteState = mapper.deleteById(id);
        sqlSession.close();
        if (deleteState==1){
            return 200;
        }
        return 404;
    }

    @Override
    public List<AllUserVO> searchByNickname(String nickname) {
        if (StringUtils.idEmpty(nickname)){
            List<AllUserVO> allUserVOList = showAllUser();
            return allUserVOList;
        }
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectByNickname(nickname);
        sqlSession.close();
        ArrayList<AllUserVO> allUserVOArrayList = conversionListUserToListAllUserVO(userList);
        return allUserVOArrayList;
    }




    private ArrayList<AllUserVO> conversionListUserToListAllUserVO(List<User> userList) {
        ArrayList<AllUserVO> allUserVOArrayList = new ArrayList<>();

        for (User user : userList) {
            AllUserVO allUserVO = new AllUserVO(user.getId(), user.getUsername(), user.getNickname(), user.getPassword(), user.getRecipient(), user.getAddress(), user.getTel());
            allUserVOArrayList.add(allUserVO);
        }
        return allUserVOArrayList;
    }
}
